<?php
class PublicAction extends Action{
	
	public function _initialize() {
		//临时验证是否使用该模块
		if(true){
			$tempverify = $_REQUEST['tempverify'];
			if(empty($tempverify))$tempverify=$_SESSION['plugininfo']['tempverify'];
			if($tempverify!='yes'){
				$this->error('暂时未开放该功能');
			}
			$_SESSION['plugininfo']['tempverify']=$tempverify;
		}
	}
	
	public function login() {
		// 已登录
		/**
		if ( service('Passport')->isLogged() ) {
			U('User://Space/index','',true);
		}
		**/
		//验证码
		$opt_verify = model('Xdata')->lget('siteopt');
		$opt_verify = $opt_verify['site_verify'];
		$opt_verify = in_array('login', $opt_verify);
		if ($opt_verify) {
			$this->assign('register_verify_on', 1);
		}
		
		$data['email'] = t($_REQUEST['email']);
		$data['uid'] = t($_REQUEST['uid']);
		//$data['list'] = D('Operate','weibo')->getIndex(3);
		
		//$this->_getThridPFLoginUrl();
		
		$this->assign($data);
		$this->assign('regInfo',model('Xdata')->lget('register'));
		
		if(!empty($_REQUEST['ajx_login'])){
			$this->display('quick_login');
		}else{
			$this->display();
		}
	}
	
	
	public function doLogin($username = '', $password = '') {
		//检查验证码
		$opt_verify = model('Xdata')->lget('siteopt');
		$opt_verify = $opt_verify['site_verify'];
		$opt_verify = in_array('login', $opt_verify);
		//echo $_POST['verify']."-".md5($_POST['verify']).'-'.$_SESSION['verify'];
		if ($opt_verify && md5($_POST['verify'])!=$_SESSION['verify']) {
			$this->error('验证码错误');
		}
		
		$username =	empty($username) ? $_POST['email']  : $username;
		$password =	empty($password) ? $_POST['password'] : $password;
		
		if(!$password){
			$this->error('请输入密码');
		}
		$passport =	service('Passport');
		$login_	  =	$passport->loginAgent($username,$password);
		//echo "登录结果".$login_;
		//dump($_SESSION);
		if($login_) {
			//检查是否激活
			if ($_SESSION['userInfo']['is_active'] == 0) {
				if(!$this->isAjax()){
					redirect(U('agent://Public/login',array('t'=>'unactive','email'=>$username,'uid'=>$_SESSION['mid'])));
					exit;
				}else{
					exit(json_encode(array('status'=>'-1','msg'=>'请去邮箱激活账户！','redirect'=>U('agent://Public/login',array('t'=>'unactive','email'=>$username,'uid'=>$_SESSION['mid'])))));
				}
				
			}
			$this->assign('jumpUrl',U('agent://Account/index'));
			$this->success($username.' 登录成功');
		}else {
			//echo "error";
			$this->error('用户名或密码错误！');
		}
	}
	
	public function logout() {
		service('Passport')->logoutLocal();
		$this->assign('jumpUrl',U('agent://Index/index'));
		$this->success('成功退出');
	}
	
	
	public function register() {
		//检查是否允许注册
		$opt_register = model('Xdata')->lget('register');
		$opt_register = $opt_register['register_type'];
		if ( $opt_register === 'closed' ) {
			$this->error('抱歉：本站已关闭注册');
		} else if ( $opt_register === 'invite' ) {
//			if ( empty($_GET['validationid']) || empty($_GET['validationcode']) ) {
//				$this->error('抱歉：目前仅接受邀请注册，请向已注册的用户索要邀请链接');
//			}else if ( ! $invite = service('Validation')->getValidation() ) {
//				$this->error('抱歉：邀请码错误');
//			}
			$invite = h($_REQUEST['invite']);
			$inviteSet = model('Invite')->getSet();
			if($inviteSet['invite_set']=='close'){
				$this->error('邀请注册功能已关闭');
			}elseif ($inviteSet['invite_set']=='common') {
				if ( !$invite ) {
					$this->error('抱歉：目前仅接受邀请注册，请向已注册的用户索要邀请链接');
				}else {
					// 检查邀请码是否合法(邀请码即为用户ID)
					if( ! M('user')->where('`uid`='.intval($invite))->find() ) {
						$this->error('抱歉：邀请码错误');
					}
				}
			}elseif ($inviteSet['invite_set']=='invitecode'){
				if ( !$invite ) {
					$this->error('抱歉：目前仅接受邀请注册，请向已注册的用户索要邀请链接');
				}else{
					$info = model('Invite')->checkInviteCode($invite);
					if(!$info){
						$this->error('抱歉：邀请码错误');
					}
					if($info['is_used']==1){
						$this->error('邀请码已被使用');
					}
					$this->assign('inviteinfo',$info);
				}
			}
		}
		
		if ($invite) {
			$this->assign('invite', $invite);
		}
		
		//验证码
		$opt_verify = model('Xdata')->lget('siteopt');
		$opt_verify = $opt_verify['site_verify'];
		$opt_verify = in_array('register', $opt_verify);
		if ($opt_verify) {
			$this->assign('register_verify_on', 1);
		}
		
		$this->display();
	}
	
	// 创建帐号
	public function doRegister() {
		//$invite = service('Validation')->getValidation();
		
		//检查是否允许注册
		$opt_register = model('Xdata')->lget('register');
		$opt_register = $opt_register['register_type'];
		
		$opt_register = 'open';
		if ( $opt_register === 'closed' ) {
			$this->error('抱歉：本站已关闭注册');
		} else if ( $opt_register === 'invite' ) {
//			if ( empty($_POST['validationid']) || empty($_POST['validationcode']) ) {
//				$this->error('抱歉：目前仅接受邀请注册，请向已注册的用户索要邀请链接');
//			}else if ( !$invite ) {
//				$this->error('抱歉：邀请码错误');
//			}
			$invite = h($_REQUEST['invitecode']);
			$inviteSet = model('Invite')->getSet();
			if($inviteSet['invite_set']=='close'){
				$this->error('邀请注册功能关闭');
			}elseif($inviteSet['invite_set']=='common'){
				$inviteinfo['uid'] = $invite;
			}else{
				$inviteinfo = model('Invite')->checkInviteCode($invite);
				if(!$inviteinfo){
					$this->error('抱歉：邀请码错误');
				}
				if($inviteinfo['is_used']==1){
					$this->error('邀请码已被使用');
				}
			}
		}
		//参数合法性检查
		$required_field = array(
			'email'		=> 'Email',
			'uname'		=> '昵称',
			'password'	=> '密码',
			'repassword'=> '密码',
		);
		foreach ($required_field as $k => $v) {
			if ( empty($_POST[$k]) ) $this->error($v . '不可为空');
		}
		
		//验证码
		$opt_verify = model('Xdata')->lget('siteopt');
		$opt_verify = $opt_verify['site_verify'];
		$opt_verify = in_array('register', $opt_verify);
		if ( $opt_verify && md5($_POST['verify'])!=$_SESSION['verify'] ) {
			$this->error('验证码错误');
		}
		
		if ( ! $this->isValidEmail($_POST['email']) ) {
			$this->error('Email格式错误，请重新输入');
		}
		if( strlen($_POST['password']) < 6 || strlen($_POST['password']) > 16 || $_POST['password'] != $_POST['repassword'] ) {
			$this->error('密码必须为6-16位，且两次必须相同');
		}
		if ( ! $this->isEmailAvailable($_POST['email']) ) {
			$this->error('Email已经被使用，请重新输入');
		}

		$validnname = $this->isValidNickName($_POST['uname']);
		if ( !$validnname ) {
			$this->error('昵称已经被使用，请重新输入');
		}
		
		// 是否需要Email激活
		$opt_email_activate = model('Xdata')->lget('register');
		$opt_email_activate = $opt_email_activate['register_email_activate'];
		
		// 注册
		$_POST['password']  = md5($_POST['password']);
		$_POST['ctime']	    = time();
		$_POST['is_active'] = $opt_email_activate == 1 ? 0 : 1;
		$_POST['is_open'] = 'Y';
		$_POST['enable'] = 'Y';
		
		$data['email'] = $_POST['email'];
		$data['uname'] = $_POST['uname'];
		$data['password'] = $_POST['password'];
		$data['ctime'] = $_POST['ctime'];
		$data['is_active'] = $_POST['is_active'];
		$data['is_open'] = $_POST['is_open'];
		$data['enable'] = $_POST['enable'];
		$data['role'] = 'agent';
		$dao = M('user');
		$uid = $dao->add($data);
		if (!$uid) $this->error('抱歉：注册失败，请稍后重试');

		
		// 将邀请码设置已用
		/**
		model('Invite')->setInviteCodeUsed($invite);
		
		// 互相关注好友
		if ( $inviteinfo['uid'] ) {
			//D('Follow','weibo')->dofollow($uid,$inviteinfo['uid']);
			//D('Follow','weibo')->dofollow($inviteinfo['uid'],$uid);
			//邀请人积分操作
			X('Credit')->setUserCredit($inviteinfo['uid'],'invite_friend');
		}
		**/
		// 邮件激活
		if ( $opt_email_activate == 1 ) {
			$this->activate($uid, $_POST['email'], $invite);
		}else {
			
			//$this->setSessionAndCookie($uid, $_POST['uname'], $_POST['email']);
			
			//$this->recordLogin($uid);
			
			// 关联操作
			//$this->registerRelation($uid, $invite);
			
			//service('Validation')->unsetValidation();	

			//注册完毕，跳转至帐号修改页
			redirect( U('agent://Account/index') );
		}
	}
	
	
	/**
	*	发送联盟会员注册激活邮件
	**/
	public function resendEmail() {
		Log::record('发送激活邮件：resendEmail()',Log::DEBUG,Log::FILE);	
		Log::save();
		$invite = service('Validation')->getValidation();
		$this->activate(intval($_GET['uid']), $_GET['email'], $invite, 1);
	}
	
	//发送激活邮件
	public function activate($uid, $email, $invite = '', $is_resend = 0) {
		//设置激活路径
		$activate_url  = service('Validation')->addValidation($uid, '', 'agent://Public/doActivate', 'register_activate', serialize($invite));
		Log::record('发送激活邮件：['.$uid.']['.$email.']['.$invite.']['.$is_resend.']'.$activate_url,Log::DEBUG,Log::FILE);	
		Log::save();
		if ($invite) {
			$this->assign('invite', $invite);
		}
		$this->assign('url',$activate_url);

		//设置邮件模板
		$body = <<<EOD
感谢您注册小心意联盟会员!<br>

请马上点击以下联盟会员注册确认链接，激活您的帐号！<br>

<a href="$activate_url" target='_blank'>$activate_url</a><br/>

如果通过点击以上链接无法访问，请将该网址复制并粘贴至新的浏览器窗口中。<br/>

如果你错误地收到了此电子邮件，你无需执行任何操作来取消帐号！此帐号将不会启动。
EOD;
		// 发送邮件
		global $ts;
		$email_sent = service('Mail')->send_email($email, "激活{$ts['site']['site_name']}联盟会员帐号",$body);
		
		// 渲染输出
		if ($email_sent) {
			$email_info = explode("@", $email);
			switch ($email_info[1]) {
				case "qq.com"    : $email_url = "mail.qq.com";break;
				case "163.com"   : $email_url = "mail.163.com";break;
				case "126.com"   : $email_url = "mail.126.com";break;
				case "gmail.com" : $email_url = "mail.google.com";break;
				default          : $email_url = "mail.".$email_info[1];
			}
			
			$this->assign("uid",$uid);
			$this->assign('email', $email);
			$this->assign('is_resend', $is_resend);
			$this->assign("email_url",$email_url);
			$this->display('activate');
		}else {
			$this->assign('jumpUrl', U('agent://Public/login'));
			$this->error('抱歉：邮件发送失败，请稍后重试');
		}
	}
	
	public function doActivate() {
		$invite = service('Validation')->getValidation();
		if (!$invite) {
			$this->assign('jumpUrl', U('agent://Public/register'));
	       	$this->error('抱歉：激活码错误，请重新注册');
		}
		$uid = $invite['from_uid'];
        
      	$user = M('user')->where("`id`=$uid")->find();

      	if ($user['is_active'] == 1) {
        	$this->assign('jumpUrl', U('agent://Public/login'));
        	$this->success('您的帐号已激活');
        	exit;
      	} else if ($user['is_active'] == 0) {
        	//激活帐户
        	$res = M('user')->where("`id`=$uid")->setField('is_active', 1);
        	if (!$res) $this->error('抱歉：激活失败');
        	
			$this->setSessionAndCookie($user['id'], $user['uname'], $user['email']);
			
			$this->recordLogin($user['id']);
			
					//关联操作
			//$this->registerRelation($user['id'], $invite);
					
			service('Validation')->unsetValidation();
		
			$this->assign('jumpUrl', U('agent://Account/index'));
			$this->success("恭喜：激活成功");
      	} else {
        	$this->assign('jumpUrl', U('agent://Public/register'));
        	$this->error('抱歉：激活码错误，请重新注册');
      	}
	}
	
	public function sendPassword() {
		$this->display();
	}
	
	public function doSendPassword() {
		$_POST["email"]	= t($_POST["email"]);
		if ( !$this->isValidEmail($_POST['email']) )$this->error('邮箱格式错误');
		
		$user =	M("user")->where('`email`="' . $_POST['email'] . '"')->find();
		
        if(!$user) {
        	$this->error("该邮箱没有注册");
        }else {
            $code = base64_encode( $user["id"] . "." . md5($user["id"] . '+' . $user["password"]) );
            $url  = SITE_URL.U('agent://Public/resetPassword', array('code'=>$code));
            $body = <<<EOD
<strong>{$user["uname"]}，你好：</strong><br/>

您只需通过点击下面的链接重置您的密码：<br/>

<a href="$url">$url</a><br/>

如果通过点击以上链接无法访问，请将该网址复制并粘贴至新的浏览器窗口中。<br/>

如果你错误地收到了此电子邮件，你无需执行任何操作来取消帐号！此帐号将不会启动。
EOD;
			
			global $ts;
			$email_sent = service('Mail')->send_email($user['email'], "重置{$ts['site']['site_name']}密码", $body);
			
            if ($email_sent) {
	            $this->assign('jumpUrl', SITE_URL);
	            $this->success("已把密码发送到你的邮箱$email中，请注意查收");
            }else {
            	$this->error('抱歉：邮件发送失败，请稍好重试');
            }
		}
	}
	
	public function resetPassword() {
		$code = explode('.', base64_decode($_GET['code']));
        $user = M('user')->where('`id`=' . $code[0])->find();
        
        if ( $code[1] == md5($code[0].'+'.$user["password"]) ) {
	        $this->assign('email',$user["email"]);
	        $this->assign('code', $_GET['code']);
	        $this->display();
        }else {
        	$this->error("抱歉：链接错误");
        }
	}
	
	public function doResetPassword() {
		if($_POST["password"] != $_POST["repassword"]) {
        	$this->error("输入的两次密码必须一致，请重新输入");
        }
        
		$code = explode('.', base64_decode($_POST['code']));
        $user = M('user')->where('`id`=' . $code[0])->find();
        
        if ( $code[1] == md5($code[0] . '+' . $user["password"]) ) {
	        $user['password'] = md5($_POST['password']);
	        $res = M('user')->save($user);
	        if ($res) {
	        	$this->assign('jumpUrl', U('agent://Public/login'));
	        	$this->success('保存成功');
	        }else {
	        	$this->error('抱歉：保存失败，请稍后重试');
	        }
        }else {
        	$this->error("抱歉：安全码错误");
        }
	}
	
	public function doModifyEmail() {
    	if ( !$validation = service('Validation')->getValidation() ) {
    		$this->error('验证码错误');
    	}
    	if ( "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"] != $validation['target_url'] ) {
    		$this->error('URL错误');
		}
    	
    	$validation['data'] = unserialize($validation['data']);
    	//dump($validation);
    	$map['id']			= $validation['from_uid'];
    	$map['email']		= $validation['data']['oldemail'];
    	//dump($map);
		if ( M('User')->where($map)->setField('email', $validation['data']['email']) ) {
			service('Validation')->unsetValidation();
			service('Passport')->logoutLocal();
			$this->assign('jumpUrl', SITE_URL);
			$this->success('激活新Email成功，请重新登录');
		}else {
			$this->error('抱歉：激活新Email失败');
		}
    }
	
	//检查Email地址是否合法
	public function isValidEmail($email) {
		return isValidEmail($email);
	}
	
	//检查Email是否可用
	public function isEmailAvailable($email = null) {
		$return_type = empty($email) ? 'ajax' 		   : 'return';
		$email		 = empty($email) ? $_POST['email'] : $email;
		
		$res = M('User')->where('`email`="'.$email.'"')->find();
		
		if ( !$res ) {
			if ($return_type === 'ajax') echo 'success';
			else return true;
		}else {
			if ($return_type === 'ajax') echo '邮箱已注册';
			else return false;
		}
	}
	
	//检查昵称是否为唯一
	
	public function isValidNickName( $name  = null){
		$return_type = empty($name) ? 'ajax' 		   : 'return';
		$name		  = empty($name) 		 ? t($_POST['uname']) 				: $name;
		if(empty($name)){
				if ($return_type === 'ajax') echo '输入昵称';
				else return false;
		}
		$res = M('user')->where("uname='{$name}'")->count();
		if ( !$res ) {
			if ($return_type === 'ajax') echo 'success';
			else return true;
		}else {
			if ($return_type === 'ajax') echo '昵称已占用';
			else return false;
		}
	}
	
	//检查是否真实姓名。支持ajax和return
	public function isValidRealName($name = null, $opt_register = null) {
		$return_type  = empty($name) 		 ? 'ajax' 							: 'return';
		$name		  = empty($name) 		 ? t($_POST['uname']) 				: $name;
		$opt_register = empty($opt_register) ? model('Xdata')->lget('register') : $opt_register;
		
		if ($opt_register['register_realname_check'] == 1) {
			$lastname = explode(',', $opt_register['register_lastname']);
			$res = in_array( substr($name, 0, 3), $lastname ) || in_array( substr($name, 0, 6), $lastname );
		}else {
			$res = true;
		}
		
		if ($res) {
			if ($return_type === 'ajax') echo 'success';
			else return true;
		}else {
			if ($return_type === 'ajax') echo 'fail';
			else return false;
		}
	}
	
	//登录记录
	public function recordLogin($uid) {
		$data['uid']	= $uid;
		$data['ip']		= get_client_ip();
		$data['place']	= convert_ip($data['ip']);
		$data['ctime'] 	= time();
		M('login_record')->add($data);
		//登陆积分
		//X('Credit')->setUserCredit($uid,'user_login');
	}
	

}
